<template>
  <div>
    <div id="select" style="display: flex">
      <el-select id="cj_select" v-model="selectedScene" placeholder="请选择战场场景">
        <el-option
          v-for="item in scenetable"
          :key="item.value"
          :label="item.label"
          :value="item.value"
          @click.native="getSslListBySceneID(item.label)"
        />
      </el-select>
      <el-select style="margin-left: 20px" id="ssl_select" v-model="selectedSSl" placeholder="请选择杀伤链">
        <el-option
          v-for="item in ssltable"
          :key="item.value"
          :label="item.label"
          :value="item.value"
          @click.native="fetchThreeChainData(item.label)"
        />
      </el-select>
    </div>
    <h3 style="margin-left: 20px">时间链展示</h3>
    <div id="Chain_chart" />
    <div id="help">
      <div id="satellite_scene" v-show="show_help==1">
        <h3 style="margin-left: 20px">卫星精度链展示</h3>
        <form @submit.prevent="submitForm">
          <h4 style="margin-left: 40px">雷达范围数据设置（单位：km）</h4>
          <div style="margin-left: 50px; display: flex; gap: 10px;">
            <el-input v-model="cone_position1[0]" placeholder="请输入战机雷达x坐标" type="number" :step="0.01"></el-input>
            <el-input v-model="cone_position1[1]" placeholder="请输入战机雷达y坐标" type="number" :step="0.01"></el-input>
            <el-input v-model="cone_position1[2]" placeholder="请输入战机雷达z坐标" type="number" :step="0.01"></el-input>
            <el-input v-model="cone_position1[3]" placeholder="请输入战机到目标中心距离处的探测半径" type="number" :step="0.01"></el-input>
            <el-input v-model="cone_position1[4]" placeholder="请输入战机雷达到目标中心距离" type="number" :step="0.01"></el-input>
          </div>
          <h4 style="margin-left: 40px">卫星探测敌方目标设置（单位：km）</h4>
          <div style="margin-left:50px; display: flex; gap: 10px;">
            <el-input v-model="cylinder_position1[0]" placeholder="请输入卫星目标x坐标" type="number" :step="0.01"></el-input>
            <el-input v-model="cylinder_position1[1]" placeholder="请输入卫星目标y坐标" type="number" :step="0.01"></el-input>
            <el-input v-model="cylinder_position1[2]" placeholder="请输入卫星目标z坐标" type="number" :step="0.01"></el-input>
            <el-input v-model="cylinder_position1[3]" placeholder="请输入卫星目标高度" type="number" :step="0.01"></el-input>
            <el-input v-model="cylinder_position1[4]" placeholder="请输入卫星目标半径" type="number" :step="0.01"></el-input>
          </div>
          <div style="text-align: center; margin-top: 20px;">
            <el-button type="primary" native-type="submit" style="min-width: 120px;">提交</el-button>
          </div>
        </form>
        <div id="demo" style="margin-top: 20px "/>
      </div>
      <div id="early_aircraft_scene" v-show="show_help==2">
        <h3 style="margin-left: 20px">预警机精度链展示</h3>
        <form @submit.prevent="submitForm2">
          <h4 style="margin-left: 40px">雷达范围数据设置（单位：km）</h4>
          <div style="margin-left: 50px; display: flex; gap: 10px;">
            <el-input v-model="cone_position2[0]" placeholder="请输入战机雷达x坐标" type="number" :step="0.01"></el-input>
            <el-input v-model="cone_position2[1]" placeholder="请输入战机雷达y坐标" type="number" :step="0.01"></el-input>
            <el-input v-model="cone_position2[2]" placeholder="请输入战机雷达z坐标" type="number" :step="0.01"></el-input>
            <el-input v-model="cone_position2[3]" placeholder="请输入战机到目标中心距离处的探测半径" type="number" :step="0.01"></el-input>
            <el-input v-model="cone_position2[4]" placeholder="请输入战机雷达到目标中心距离" type="number" :step="0.01"></el-input>
          </div>
          <h4 style="margin-left: 40px">预警机探测敌方目标设置（单位：km）</h4>
          <div style="margin-left:50px; display: flex; gap: 10px;">
            <el-input v-model="sphere_position2[0]" placeholder="请输入预警机目标x坐标" type="number" :step="0.01"></el-input>
            <el-input v-model="sphere_position2[1]" placeholder="请输入预警机目标y坐标" type="number" :step="0.01"></el-input>
            <el-input v-model="sphere_position2[2]" placeholder="请输入预警机目标z坐标" type="number" :step="0.01"></el-input>
            <el-input v-model="sphere_position2[3]" placeholder="请输入预警机目标半径" type="number" :step="0.01"></el-input>
          </div>
          <div style="text-align: center; margin-top: 20px;">
            <el-button type="primary" native-type="submit" style="min-width: 120px;">提交</el-button>
          </div>
        </form>
        <div id="demo2" style="margin-top: 20px "/>
      </div>
    </div>
  </div>
</template>
<script>
import axios from 'axios'
import 'echarts-gl'
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import {error} from "autoprefixer/lib/utils";
import {
  getList,
  getChainInfo,
  getSslListBySceneID,
  getSceneList,
  getTimeChainBySSLID,
  getPrecisionChainBySSLID
} from '@/api/ssl'
// import { response } from 'express'
export default {
  components: {},
  data() {
    return {
      cone_position1:[6,0,0,2,5],
      cylinder_position1:[0,0,0,1,4],
      cone_position2:[6,0,0,2,5],
      sphere_position2:[0,0,0,1],
      scene: null,
      camera: null,
      renderer: null,
      scene2: null,
      camera2: null,
      renderer2: null,
      scenetable:[{value:'选项1',label:'战场场景1'}],
      ssltable: [{value:'选项1',label:'杀伤链1'},{value:'选项2',label:'杀伤链2'}],
      selectedScene: null,
      selectedSSl:null,
      timeChain:{
        // title: {
        //   text: '时间链展示'
        // },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            var tar = params[1]
            return tar.name + '<br/>' + tar.seriesName + ' : ' + tar.value + 's' // 在这里加上's'
          }
        },
        grid: {
          left: '3%',
          right: '0%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          name: '事件',
          nameLocation: 'end',
          splitLine: { show: false },
          axisLabel: {
            rotate: 45 // 旋转角度
          },
          data: []
        },
        yAxis: {
          type: 'value',
          name: '时间T/s'
        },
        series: [
          {
            name: 'Placeholder',
            type: 'bar',
            stack: 'Total',
            itemStyle: {
              borderColor: 'transparent',
              color: 'transparent'
            },
            emphasis: {
              itemStyle: {
                borderColor: 'transparent',
                color: 'transparent'
              }
            },
            data: []
          },
          {
            name: '时间耗费',
            type: 'bar',
            stack: 'Total',
            label: {
              show: true,
              position: 'inside'
            },
            data: []
          }
        ]
      },
      precisionChain:null,
      accuracyChain:null,
      show_help:1
    }
  },
  computed: {},
  created() {},
  mounted() {
    this.getScene()
    this.drawLine()
    this.createhelp()
    this.createThreeScene()
  },
  methods: {
    //获取所有场景列表
    getScene(){
      getSceneList()
        .then(response=>{
          this.scenetable=response.data.map(item=>{
            return{
              value:'选项'+item.sceneId,//设置value的值
              label:'战场场景'+item.sceneId//设置label的值
            }
          })
        })
    },
    //根据给定的场景ID来获取杀伤链列表
    getSslListBySceneID(selectedValue){
      const ssl_id = parseInt(selectedValue.match(/\d+/)[0])
      getSslListBySceneID(ssl_id)
        .then(response=>{
          this.ssltable=response.data.map(item=>{
            return{
              value:'选项'+item.sslId,//设置value的值
              label:'杀伤链'+item.sslId//设置label的值
            }
          })
        })
    },
    submitForm(){
      while(this.scene.children.length > 0){
        this.scene.remove(this.scene.children[0]);
      }
      this.createThreeScene()
    },
    submitForm2(){
      while(this.scene2.children.length > 0){
        this.scene2.remove(this.scene2.children[0]);
      }
      this.createThreeScene2()
    },
    //获取三条链的信息
    fetchThreeChainData(selectedValue){
      console.log("response.data");
      const ssl_id = parseInt(selectedValue.match(/\d+/)[0])
      getPrecisionChainBySSLID(ssl_id)
        .then(response=>{
          let temp_data = response.data
          console.log(temp_data)
          if(temp_data.satelliteDetectionPosition==null){
            console.log("卫星为空");
            var early_wraning_detection_position = temp_data.earlyWraningDetectionPosition.split(',');
            var early_wraning_detection_position_int = early_wraning_detection_position.map(function (coordinate) {
              return parseFloat(coordinate, 10);
            });
            this.sphere_position2 = early_wraning_detection_position_int;
            var fighter_position = temp_data.fighterPosition.split(',');
            var fighter_position_int = fighter_position.map(function (coordinate){
              return parseFloat(coordinate, 10);
            });
            this.cone_position2 = fighter_position_int;
            this.show_help=2;
            while(this.scene2.children.length > 0){
              this.scene2.remove(this.scene2.children[0]);
            }
            this.createThreeScene2()
            console.log(this.sphere_position2[3]);
          }else if(temp_data.earlyWraningDetectionPosition==null){
            console.log("预警机为空");
            console.log(temp_data.satelliteDetectionPosition)
            console.log(temp_data.fighterPosition)
            var satellite_detection_position = temp_data.satelliteDetectionPosition.split(',');
            var satellite_detection_position_int = satellite_detection_position.map(function (coordinate) {
              return parseFloat(coordinate, 10);
            });
            this.cylinder_position1 = satellite_detection_position_int;
            var fighter_position = temp_data.fighterPosition.split(',');
            var fighter_position_int = fighter_position.map(function (coordinate){
              return parseFloat(coordinate, 10);
            });
            this.show_help=1;
            while(this.scene.children.length > 0){
              this.scene.remove(this.scene.children[0]);
            }
            this.cone_position1 = fighter_position_int;
            this.createThreeScene()
            
          }
        })
      getTimeChainBySSLID(ssl_id)
        .then(response=>{
          let tempData = response.data.data
          tempData=eval(tempData)
          console.log(tempData)
          // const correctedData = tempData.data.replace(/'/g, '"').replace(/(\w+):/g, '"$1":');
          // const parsedData = JSON.parse(correctedData);
          // console.log(parsedData)
          this.timeChain.series[0].data=[]
          this.timeChain.series[1].data=[]
          this.timeChain.xAxis.data=[]
          tempData.forEach(item=>{
            this.timeChain.series[0].data.push(item.value);
            this.timeChain.series[1].data.push(item.value);
            this.timeChain.xAxis.data.push(item.description);
          })
          console.log("this.timeChain.series[0].data"+this.timeChain.series[0].data)
          let prefixSum = 0
          const newArray = [0]
          for(let i=0;i<this.timeChain.series[0].data.length;i++){
            prefixSum+=this.timeChain.series[0].data[i]
            newArray.push(prefixSum)
          }
          console.log("newArray"+newArray)
          this.timeChain.series[0].data = newArray
          this.drawLine()
        })
    },
    drawLine() {
      // 基于准备好的dom，初始化echarts实例
      const Chain_chart = this.$echarts.init(document.getElementById('Chain_chart'))
      Chain_chart.setOption(this.timeChain)
    },
    createhelp(){
      this.scene = new THREE.Scene()
      this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000)
      this.renderer = new THREE.WebGLRenderer()
      this.scene2 = new THREE.Scene()
      this.camera2 = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000)
      this.renderer2 = new THREE.WebGLRenderer()
    },
    createThreeScene() {
      this.renderer.setClearColor(0xFFFFFF)
      this.renderer.setSize(window.innerWidth*0.8, window.innerHeight)
      this.renderer.domElement.style.border = '1px solid #000'
      document.getElementById('demo').appendChild(this.renderer.domElement)

      // 定义圆锥体的参数
      var cone_x = this.cone_position1[0]
      var cone_y = this.cone_position1[1]
      var cone_z = this.cone_position1[2]
      var cone_r = this.cone_position1[3]
      var cone_h = this.cone_position1[4]
      var radialSegments = 32
      var conegeometry = new THREE.ConeGeometry(cone_r, cone_h, radialSegments)

      // 创建线框网格材质
      var wireframeMaterial1 = new THREE.LineBasicMaterial({ color: 0x000000 }); // 设置线框材质
      var wireframeGeometry1 = new THREE.WireframeGeometry(conegeometry);
      var wireframe1 = new THREE.LineSegments(wireframeGeometry1, wireframeMaterial1);

      this.scene.add(wireframe1)
      cone_x = cone_x-cone_h/2

      wireframe1.rotation.z = -Math.PI/2

      // 定义圆柱体的参数
      var cylinder_x = this.cylinder_position1[0]
      var cylinder_y = this.cylinder_position1[1]
      var cylinder_z = this.cylinder_position1[2]
      var cylinderRadius = this.cylinder_position1[3];
      var cylinderHeight = this.cylinder_position1[4];
      var cylinderGeometry = new THREE.CylinderGeometry(cylinderRadius, cylinderRadius, cylinderHeight, 16);

      // 创建线框网格材质
      var wireframeMaterial = new THREE.LineBasicMaterial({ color: 0xff0000 }); // 紫色线框材质
      var wireframeGeometry = new THREE.WireframeGeometry(cylinderGeometry);
      var wireframe = new THREE.LineSegments(wireframeGeometry, wireframeMaterial);

      this.scene.add(wireframe);
      wireframe.position.set(cylinder_x, cylinder_y, cylinder_z); // 设置线框网格的位置
      wireframe1.position.set(cone_x,cone_y,cylinder_z)

      // this.camera.position.set((cone_x+cylinder_x)/2, (cone_y+cylinder_y)/2, (cone_z+cylinder_z)/2+1.5*cone_r)
      this.camera.position.set((cone_x+cylinder_x)/2, (cone_y+cylinder_y)/2, (cone_z+cylinder_z)/2+cone_h/2+cylinderHeight)
      this.camera.lookAt((cone_x+cylinder_x)/2, (cone_y+cylinder_y)/2, (cone_z+cylinder_z)/2)
      // 创建 OrbitControls 控制器
      const controls = new OrbitControls(this.camera, this.renderer.domElement);
      // 设置控制器的初始位置
      controls.target.set(0,0,0); // 控制器的焦点位置
      controls.update();

      let _this = this;
      function animate() {
        requestAnimationFrame( animate );
        controls.update();
        _this.renderer.render( _this.scene, _this.camera );
      }
      animate()
    },
    createThreeScene2() {
      this.renderer2.setClearColor(0xFFFFFF)
      this.renderer2.setSize(window.innerWidth*0.8, window.innerHeight)
      this.renderer2.domElement.style.border = '1px solid #000'
      document.getElementById('demo2').appendChild(this.renderer2.domElement)

      // 定义圆锥体的参数
      var cone_x = this.cone_position2[0]
      var cone_y = this.cone_position2[1]
      var cone_z = this.cone_position2[2]
      var cone_r = this.cone_position2[3]
      var cone_h = this.cone_position2[4]
      var radialSegments = 32
      var conegeometry = new THREE.ConeGeometry(cone_r, cone_h, radialSegments)

      // 创建线框网格材质
      var wireframeMaterial1 = new THREE.LineBasicMaterial({ color: 0x000000 }); // 设置线框材质
      var wireframeGeometry1 = new THREE.WireframeGeometry(conegeometry);
      var wireframe1 = new THREE.LineSegments(wireframeGeometry1, wireframeMaterial1);

      this.scene2.add(wireframe1)
      cone_x = cone_x-cone_h/2

      wireframe1.rotation.z = -Math.PI/2

      // 定义圆柱体的参数
      var sphere_x = this.sphere_position2[0]
      var sphere_y = this.sphere_position2[1]
      var sphere_z = this.sphere_position2[2]
      var sphere_r = this.sphere_position2[3];
      var SphereGeometry = new THREE.SphereGeometry(sphere_r,16,16);

      // 创建线框网格材质
      var wireframeMaterial = new THREE.LineBasicMaterial({ color: 0xff0000 }); // 线框材质
      var wireframeGeometry = new THREE.WireframeGeometry(SphereGeometry);
      var wireframe = new THREE.LineSegments(wireframeGeometry, wireframeMaterial);

      this.scene2.add(wireframe);
      wireframe.position.set(sphere_x, sphere_y, sphere_z); // 设置线框网格的位置
      wireframe1.position.set(cone_x,cone_y,sphere_z)
      // this.camera.position.set((cone_x+cylinder_x)/2, (cone_y+cylinder_y)/2, (cone_z+cylinder_z)/2+1.5*cone_r)
      this.camera2.position.set((cone_x+sphere_x)/2+cone_h/2, (cone_y+sphere_y)/2, (cone_z+sphere_z)/2+cone_h+sphere_r)
      this.camera2.lookAt((cone_x+sphere_x)/2, (cone_y+sphere_y)/2, (cone_z+sphere_z)/2)
      // 创建 OrbitControls 控制器
      const controls = new OrbitControls(this.camera2, this.renderer2.domElement);
      // 设置控制器的初始位置
      controls.target.set(0,0,0); // 控制器的焦点位置
      controls.update();

      let _this = this;
      function animate() {
        requestAnimationFrame( animate );
        controls.update();
        _this.renderer2.render( _this.scene2, _this.camera2 );
      }
      animate()
    }
  }
}
</script>
<style lang='scss'>
#cj_select{
  margin-top: 20px;
  margin-bottom: 20px;
  margin-left: 20px;
}
#ssl_select{
  margin-top: 20px;
  margin-bottom: 20px;
  margin-left: 20px;
}
#Chain_chart {
  width: 100%;
  height: 60vh; /* 设置为视口高度的60% 或其他百分比值 */
  box-sizing: border-box; /* 使用 border-box 模型，保持边框和内边距的稳定性 */
}


#demo {
  width: 80%;
  // color: transparent;
}
</style>
